import * as echarts from 'echarts'
import { addListener, removeListener } from 'resize-detector'

import Vue from 'vue'
Vue.prototype.$echarts = echarts

// 地图数据
const modulesFiles = require.context('@/assets/map-js', true, /\.js$/)
modulesFiles.keys().reduce((modules, modulePath) => {
  modulesFiles(modulePath)
}, {})

export default {
  data() {
    return {
      instance: ''
    }
  },

  props: {
    option: {
      type: Object,
      default: () => {}
    },
    loading: {
      type: Boolean,
      default: false
    }
  },

  watch: {
    option: {
      deep: true,
      handler(newValue) {
        this.instance.setOption(newValue)
      }
    },
    loading: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (!this.instance) return

        if (newValue) {
          this.instance.showLoading({
            text: '数据加载中',
            zlevel: 0
          })
        }
        if (!newValue) {
          this.instance.hideLoading()
        }
      }
    }
  },

  methods: {
    init() {
      this.$nextTick(() => {
        const chartDom = this.$refs.chartDom

        this.instance = echarts.init(chartDom)
        this.instance.setOption(this.option)

        addListener(chartDom, this.resize)
      })
    },

    resize() {
      this.instance.resize()
    }
  },

  created() {
    this.init()
  },

  beforeDestroy() {
    removeListener(this.$refs.chartDom, this.resize)
    this.instance.dispose()
    this.instance = null
  },

  render() {
    return <div ref="chartDom" style="height:100%;width:100%"></div>
  }
}
